<?php
	class ConfigModel extends CI_Model {
		// 表名
		static $tableName = "sys_config";
		static $schoolConfigTable = "school_config";


	    public function __construct() {
	        parent::__construct();
	    }

	    // 根据配置项，获取配置信息
	    public function get_config_info($key, $returnValue = false){
	    	$this->db->where("config_key", $key);
	    	$configInfo = $this->db->get(self::$tableName)->row_array();
	    	return $returnValue ? $configInfo['config_value'] : $configInfo;
	    }

	    // 获取配置列表
	    public function get_config_data(){
    		return $this->db->get(self::$tableName)->result_array();
	    }

	    // 更新配置项
	    public function set_config_value($key, $value){
	    	$configInfo = $this->get_config_info($key);
	    	// 配置值
	    	$data['config_key'] = $key;
	    	$data['config_value'] = $value;
	    	$data['createtime'] = date("Y-m-d H:i:s");
	    	// 写入配置信息
	    	if($configInfo) {
	    		$this->db->update(self::$tableName, $data, "id='{$configInfo['id']}'");
	    	} else {
	    		$this->db->insert(self::$tableName, $data);
	    	}
	    }

	    // 获取学校配置
	    public function get_school_campus_config($schoolId, $campusId, $key){
	    	$this->db->where("school_id", $schoolId);
	    	$this->db->where("campus_id", $campusId);
	    	$this->db->where("config_key", $key);
	    	return $this->db->get(self::$schoolConfigTable)->row_array();
	    }
	    // 保存学校配置
	    public function save_school_campus_config($schoolId, $campusId, $key, $value){
	    	$configInfo = $this->get_school_campus_config($schoolId, $campusId, $key);
	    	// 检查是否有存在旧的配置信息
	    	if($configInfo) {
	    		$update['config_value'] = $value;
	    		$this->db->update(self::$schoolConfigTable, $update, "id='{$configInfo['id']}'");
	    	} else {
	    		// 入库
	    		$insert['school_id'] = $schoolId;
	    		$insert['campus_id'] = $campusId;
	    		$insert['config_key'] = $key;
	    		$insert['config_value'] = $value;
	    		$insert['createtime'] = date("Y-m-d H:i:s");
	    		$this->db->insert(self::$schoolConfigTable, $insert);
	    	}
		}
	    // 获取学校配置（不分校区）
	    public function get_school_config($schoolId, $key){
	    	$this->db->where("school_id", $schoolId);
	    	$this->db->where("config_key", $key);
	    	return $this->db->get(self::$schoolConfigTable)->row_array();
	    }
	    // 保存学校配置（不分校区）
	    public function save_school_config($schoolId, $key, $value){
	    	$configInfo = $this->get_school_config($schoolId, $key);
	    	// 检查是否有存在旧的配置信息
	    	if($configInfo) {
	    		$update['config_value'] = $value;
	    		$this->db->update(self::$schoolConfigTable, $update, "id='{$configInfo['id']}'");
	    	} else {
	    		// 入库
	    		$insert['school_id'] = $schoolId;
	    		// $insert['campus_id'] = 0;
	    		$insert['config_key'] = $key;
	    		$insert['config_value'] = $value;
	    		$insert['createtime'] = date("Y-m-d H:i:s");
	    		$this->db->insert(self::$schoolConfigTable, $insert);
	    	}
	    }
	}